package view;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ThymeleafConfig implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();

        //1.创建TemplateEngine实例
        TemplateEngine engine = new TemplateEngine();

        //2.创建resolver对象
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context);
        resolver.setPrefix("WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");

        //3.关联resolver和engine对象
        engine.setTemplateResolver(resolver);

        //4.把engine对象放到ServletContext中
        context.setAttribute("engine",engine);
        System.out.println("初始化Template完成");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
